package com.suyang.syt.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.suyang.syt.dao.interfaces.PermissionDao;
import com.suyang.syt.dao.interfaces.RoleDao;
import com.suyang.syt.dao.interfaces.RoleResourcesPermissionDao;
import com.suyang.syt.dao.interfaces.UserRoleDao;
import com.suyang.syt.model.Permission;
import com.suyang.syt.model.Role;
import com.suyang.syt.model.RoleResourcesPermission;
import com.suyang.syt.model.dto.AjaxObj;
import com.suyang.syt.model.dto.OperationPermission;
import com.suyang.syt.model.dto.PagerEasyUI;
import com.suyang.syt.model.dto.RoleDTO;
import com.suyang.syt.service.interfaces.RoleService;
import com.suyang.syt.util.EmptyUtil;

@Service
public class RoleServiceImpl implements RoleService {
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private UserRoleDao userRoleDao;
	@Autowired
	private PermissionDao permissionDao;
	@Autowired
	private RoleResourcesPermissionDao roleResourcesPermissionDao;

	@Override
	public AjaxObj add(RoleDTO roleDTO) throws Exception {
		if (roleDTO != null && EmptyUtil.isNotEmpty(roleDTO.getName())) {
			if (roleDao.countName(roleDTO.getName()) > 0) {
				return new AjaxObj(0, "已经存在该角色名，请重新添加!");
			}
			Role role = new Role();
			role.setCreateName(roleDTO.getCreateName());
			role.setCreateTime(roleDTO.getCreateTime());
			role.setDescribes(roleDTO.getDescribes());
			role.setName(roleDTO.getName());
			roleDao.add(role);
			return new AjaxObj(1, "增加成功！");
		}
		return new AjaxObj(0, "增加失败！");
	}

	@Override
	public AjaxObj deletes(String roleIds) throws Exception {
		if (EmptyUtil.isNotEmpty(roleIds)) {
			if (userRoleDao.countUserRole(roleIds) > 0) {
				return new AjaxObj(0, "要删除的角色中还有用户，不能删除！");
			}
			roleDao.deletes(roleIds);
			return new AjaxObj(1, "删除角色成功！");
		}
		return new AjaxObj(0, "请选择要删除的记录！");
	}

	@Override
	public AjaxObj update(RoleDTO roleDTO) throws Exception {
		if (roleDTO != null && EmptyUtil.isNotEmpty(roleDTO.getName())) {
			Role role = roleDao.load(roleDTO.getId());
			if (role != null) {
				if (!roleDTO.getName().equals(role.getName()) && roleDao.countName(roleDTO.getName()) > 0) {
					return new AjaxObj(0, "已经存在该角色名，请重新添加！");
				}
				role.setModifyName(roleDTO.getModifyName());
				role.setCreateTime(roleDTO.getModifyTime());
				role.setName(roleDTO.getName());
				role.setDescribes(roleDTO.getDescribes());
				roleDao.update(role);
				return new AjaxObj(1, "更新成功！");
			}
		}
		return new AjaxObj(0, "更新失败！");
	}

	@Override
	public PagerEasyUI<Role> listByEasyUI(int page, int rows, String sort, String order, String name, int roleType) throws Exception {
		StringBuilder hql = new StringBuilder(" from Role r where r.name != '超级管理员' ");
		if (EmptyUtil.isNotEmpty(name)) {
			hql.append(" and r.name like '%").append(name).append("%' ");
		}
		if (roleType > 0) {
			hql.append(" and r.roleType=").append(roleType);
		}
		if (EmptyUtil.isNotEmpty(sort)) {
			hql.append(" order by r.").append(sort);
		}
		if (EmptyUtil.isNotEmpty(order)) {
			hql.append(" ").append(order);
		}
		PagerEasyUI<Role> easyUIPager = new PagerEasyUI<Role>();
		List<Role> roles = roleDao.findByEasyUI(hql.toString(), page, rows);
		easyUIPager.setRows(roles);
		easyUIPager.setTotal((Long) roleDao.queryByHql(" select count(*) " + hql.substring(0, hql.indexOf("order by"))));
		return easyUIPager;
	}

	@Override
	public AjaxObj deleteClearUser(String roleIds) throws Exception {
		if (EmptyUtil.isNotEmpty(roleIds)) {
			userRoleDao.clearUsers(roleIds);
			return new AjaxObj(1, "成功清除了该角色中的用户,可以删除该角色了！");
		}
		return new AjaxObj(0, "清空用户失败,请选择您要清空的角色列表！");
	}

	@Override
	public Role load(long roleId) throws Exception {
		return roleDao.load(roleId);
	}

	@Override
	public List<OperationPermission> operatiaonList(long roleId, long resourcesId) throws Exception {
		List<Permission> permissions = permissionDao.list("from Permission");
		List<RoleResourcesPermission> roleResourcesPermissions = roleResourcesPermissionDao.list("from RoleResourcesPermission where resourceId=? and roleId=?", new Object[] { resourcesId, roleId });
		int p[] = new int[666];
		if (EmptyUtil.isNotEmpty(roleResourcesPermissions)) {
			RoleResourcesPermission roleResourcesPermission = roleResourcesPermissions.get(0);
			if (EmptyUtil.isNotEmpty(roleResourcesPermission.getPermissionIds())) {
				String[] rrp = roleResourcesPermission.getPermissionIds().split(",");
				for (int i = 0; i < rrp.length; i++) {
					++p[Integer.parseInt(rrp[i])];
				}
			}
		}
		List<OperationPermission> operationPermissions = new ArrayList<OperationPermission>();
		for (Permission permission : permissions) {
			// 获取当前角色权限
			if (p[(int) permission.getId()] == 1) {
				operationPermissions.add(new OperationPermission(permission.getId(), true, permission.getName()));
			} else {
				operationPermissions.add(new OperationPermission(permission.getId(), false, permission.getName()));
			}
		}
		return operationPermissions;
	}

	@Override
	public AjaxObj updateResource(long roleId, String resourceIds) throws Exception {
		List<RoleResourcesPermission> roleResourcesPermissions = roleResourcesPermissionDao.list("from RoleResourcesPermission where resourceId not in (" + resourceIds + ") and roleId=" + roleId + "");
		String ids = "";
		for (RoleResourcesPermission roleResourcesPermission : roleResourcesPermissions) {
			ids += roleResourcesPermission.getResourceId() + ",";
		}
		if (ids != null & ids != "") {
			ids = ids.substring(0, ids.length() - 1);
			roleResourcesPermissionDao.executeByHql("update RoleResourcesPermission set isDelete=1 where resourceId in (" + ids + ") and roleId=" + roleId + "");
		}
		String[] resourceArray = resourceIds.split(",");
		int t[] = new int[666];
		for (int i = 0; i < resourceArray.length; i++) {
			long resourceId = Long.parseLong(resourceArray[i]);
			if (resourceId != 1 && (++t[(int) resourceId]) <= 1) {
				RoleResourcesPermission roleResourcesPermission = roleResourcesPermissionDao.loadByRoleIdResourceId(roleId, resourceId);
				if (roleResourcesPermission == null) {
					roleResourcesPermissionDao.add(new RoleResourcesPermission(roleId, resourceId));
				} else {
					if (roleResourcesPermission.getIsDelete() == 1) {
						roleResourcesPermission.setIsDelete(0);
						roleResourcesPermissionDao.update(roleResourcesPermission);
					}
				}
			}
		}
		return new AjaxObj(1, "更新角色资源成功!");
	}

	@Override
	public AjaxObj updatePermission(long roleId, long resourceId, String permissionIds) throws Exception {
		permissionIds = permissionIds.replace("%2C", ",");
		RoleResourcesPermission roleResourcesPermission = roleResourcesPermissionDao.loadByRoleIdResourceId(roleId, resourceId);
		if (roleResourcesPermission == null) {
			roleResourcesPermissionDao.add(new RoleResourcesPermission(roleId, resourceId, permissionIds));
		} else {
			roleResourcesPermission.setPermissionIds(permissionIds);
			roleResourcesPermissionDao.update(roleResourcesPermission);
		}
		return new AjaxObj(1, "更新角色资源成功!");
	}
}